import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/services/site/site_services.dart';
import 'package:yt_devops/utils/brn_row1_delegate.dart';

class VideoMonitorSettingController extends GetxController {
  final TextEditingController factoryController = TextEditingController();
  final TextEditingController urlController = TextEditingController();
  final TextEditingController directUrlController = TextEditingController();
  final TextEditingController userIdController = TextEditingController();
  final TextEditingController appKeyController = TextEditingController();
  final TextEditingController secretKeyController = TextEditingController();
  final TextEditingController androidController = TextEditingController();
  final TextEditingController iosController = TextEditingController();
  bool isOpen = false;
  bool isSsoJump = false;
  SiteServices siteServices = Get.put(SiteServices());
  String siteId = '';
  List<dynamic> factoryList = [];
  List<dynamic> appList = [];
  List<dynamic> iosAppList = [];
  List<dynamic> androidAppList = [];
  String androidAppId = '';
  String iosAppId = '';
  String factoryId = '';
  bool isCanSubmit = false;
  @override
  void onInit() {
    super.onInit();
    if (Get.arguments != null && Get.arguments['siteId'] != null) {
      siteId = Get.arguments['siteId'].toString();
    }
  }

  @override
  void onReady() {
    if(siteId.isNotEmpty)getSiteVideoMonitorInfo();
  }

  /// 获取视频监控配置信息
  getSiteVideoMonitorInfo() async {
    showLoading();
    var result = await siteServices.getSiteVideoMonitorInfo({'siteId': siteId},
        onError: (error) {
      dismissLoading();
      handleException(error);
      return false;
    });
    dismissLoading();
    if (result != null) {
      isOpen = result['monitorStatus'].toString() == '1' ? true : false;
      isSsoJump = result['jumpMethod'].toString() == '1' ? true : false;
      factoryController.text =
          result['factoryName'] != null ? result['factoryName'].toString() : '';
      factoryId =
          result['factoryId'] != null ? result['factoryId'].toString() : '';
      androidAppId = result['androidAppId'] != null ? result['androidAppId'].toString() : '';
      iosAppId = result['iosAppId'] != null ? result['iosAppId'].toString() : '';
      directUrlController.text = result['url'] != null ? result['url'].toString() : '';
      getAppName();
      if (result['config'] != null) {
        Map<String, dynamic> map = json.decode(result['config'].toString());
        if (map != null && map['SSOUrl'] != null) {
          urlController.text = map['SSOUrl'].toString();
        }
        if (map != null && map['userId'] != null) {
          userIdController.text = map['userId'].toString();
        }
        if (map != null && map['appKey'] != null) {
          appKeyController.text = map['appKey'].toString();
        }
        if (map != null && map['secretKey'] != null) {
          secretKeyController.text = map['secretKey'].toString();
        }
      }
    }
    checkoutCanCommit();
  }

  getAppName() async {
    showLoading();
    List result = await siteServices.getVideoMonitorAppList(onError: (error) {
      dismissLoading();
      handleException(error);
      return false;
    });
    dismissLoading();
    if (result != null && result.isNotEmpty) {
      appList = result;
      if(appList.isNotEmpty){
        for (var element in appList) {
            if(element['id'].toString() == iosAppId){
              iosController.text = element['name'].toString();
            }
            if(element['id'].toString() == androidAppId){
              androidController.text = element['name'].toString();
            }
        }
      }
    }
    update();
  }
  getFactoryList() async {
    showLoading();
    var result =
        await siteServices.getVideoMonitorFactoryList(onError: (error) {
      dismissLoading();
      handleException(error);
      return false;
    });
    dismissLoading();
    if (result != null) {
      factoryList = result;
      showBottomPop(0, factoryList);
    }
    update();
  }

  getAppList(int type,) async {
    showLoading();
    List result = await siteServices.getVideoMonitorAppList(onError: (error) {
      dismissLoading();
      handleException(error);
      return false;
    });
    dismissLoading();
    if (result != null && result.isNotEmpty) {
      appList = result;
      handleAppData(type);
    }
    update();
  }
  checkoutCanCommit() {
    if(!isOpen){
      isCanSubmit = true;
    }else{

      if(!isSsoJump){
        Log.d('isSsoJump==');
        if (directUrlController.text.isNotEmpty) {
          isCanSubmit = true;
        } else {
          isCanSubmit = false;
        }
      }else{
        if (factoryId.isNotEmpty && urlController.text.isNotEmpty && userIdController.text.isNotEmpty
        && appKeyController.text.isNotEmpty && secretKeyController.text.isNotEmpty
        ) {
          isCanSubmit = true;
        } else {
          isCanSubmit = false;
        }
      }
    }
    update();
  }

  cancel(){
    Get.back();
  }
  @override
  void onClose() {}

  ///保存数据
  save() async {
    var map = {
      'siteId': siteId,
      'monitorStatus': isOpen ? 1 : 0,
      'jumpMethod': isSsoJump ? 1 : 0,
    };

    if (iosAppId.isNotEmpty) {
      map['iosAppId'] = iosAppId;
    }
    if (androidAppId.isNotEmpty) {
      map['androidAppId'] = androidAppId;
    }

    if (isSsoJump) {
      if (factoryId.isNotEmpty) {
        map['factoryId'] = factoryId;
      }
      Map jsonMap = {};
      if (urlController.text.isNotEmpty) {
        jsonMap['SSOUrl'] = urlController.text;
      }
      if (userIdController.text.isNotEmpty) {
        jsonMap['userId'] = userIdController.text;
      }
      if (appKeyController.text.isNotEmpty) {
        jsonMap['appKey'] = appKeyController.text;
      }
      if (secretKeyController.text.isNotEmpty) {
        jsonMap['secretKey'] = secretKeyController.text;
      }
      String jsonStr = json.encode(jsonMap);
      map['config'] = jsonStr;
    } else {
      if (directUrlController.text.isNotEmpty) {
        map['url'] = directUrlController.text;
      }
    }
    showLoading();
    var result =
        await siteServices.updateSiteVideoMonitorInfo(map, onError: (error) {
      dismissLoading();
      handleException(error);
      return false;
    });
    dismissLoading();
    if (result != null) {
      showSuccessToast(ResKey.mineUserManagerSaveSuccess.tr);
      Future.delayed(const Duration(milliseconds: 2000), () {
        Get.back();
      });
    }
  }

  ///处理app数据
  handleAppData(int type) {
    iosAppList.clear();
    androidAppList.clear();
    for (var element in appList) {
      if (element['sysFlag'].toString() == '0') {
        //0为安卓 1为iOS
        androidAppList.add(element);
      } else {
        iosAppList.add(element);
      }
    }
    if (type == 1) {
      showBottomPop(1, androidAppList);
    } else if (type == 2) {
      showBottomPop(2, iosAppList);
    }
  }

  ///选择厂家
  chooseFactory() {
    if (factoryList.isNotEmpty) {
      showBottomPop(0, factoryList);
    } else {
      getFactoryList();
    }
  }

  ///选择app
  chooseApp(int type) {
    if (appList.isNotEmpty) {
      handleAppData(type);
    } else {
      getAppList(type);
    }
  }

  ///弹出底部弹窗
  showBottomPop(int index, List list) {
    //0为所属单元 1为产品类型 2为产品型号
    var title = ResKey.producer.tr;
    if (index == 1) {
      title = ResKey.androidAppName.tr;
    } else if (index == 2) {
      title = ResKey.iOSAppName.tr;
    }
    if (list.isNotEmpty) {
      List<String> showList = [];
      for (var element in list) {
        showList.add(element['name'].toString());
      }
      BrnMultiDataPicker(
        context: Get.context!,
        title: title,
        confirmClick: (indexList) {
          if (index == 0) {
            factoryId = list[indexList[0]]['id'].toString();
            factoryController.text = list[indexList[0]]['name'].toString();
          } else if (index == 1) {
            androidAppId = list[indexList[0]]['id'].toString();
            androidController.text = list[indexList[0]]['name'].toString();
          } else if (index == 2) {
            iosAppId = list[indexList[0]]['id'].toString();
            iosController.text = list[indexList[0]]['name'].toString();
          }
          update();
        },
        delegate: Brn1RowDelegate(showList),
      ).show();
    }
  }
}
